package com.zz.inventory.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.zz.inventory.domain.FranchiseBills;
import com.zz.inventory.domain.FranchisePackages;
import com.zz.inventory.domain.FranchisePayments;
import com.zz.inventory.feign.InventoryService;
import com.zz.inventory.service.IFranchiseBillsService;
import com.zz.inventory.service.IFranchisePaymentsService;
import com.zz.inventory.service.impl.PackageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.example.dto.SchoolPackageRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@RestController
@Log4j2
public class PackageController {
    @Autowired
    IFranchiseBillsService iFranchiseBillsService;

    @Autowired
    IFranchisePaymentsService iFranchisePaymentsService;


    @Autowired
    InventoryService inventoryService;

    @Autowired
    PackageService packageService;



    /**
     * 生成账单
     * @param packageData
     * @return
     */
    @PostMapping("/your-api-url")
    public AjaxResult handleSubmit(@RequestBody FranchisePackages packageData) {

            Long userId = getCurrentUserId();
            // 调用Service层的事务方法
            packageService.createPackageAndSchoolRecord(packageData, userId);
            return AjaxResult.success("操作成功");
    }


    private Date calculateEndTime(Date startTime, Long serviceYears) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.YEAR, serviceYears.intValue()); // 按年计算
        return calendar.getTime();
    }

    private Long getCurrentUserId() {
        return SecurityUtils.getUserId();
    }


    /**
     * 生成订单
     * @param fr
     * @return
     */
    private AjaxResult createPaymentRecord(FranchiseBills fr) {
       try {
           FranchisePayments payments = new FranchisePayments();
           //账单ID
           payments.setAmount(fr.getAmount());   //金额
//           payments.setPaymentTime(new Date());   //支付时间
           payments.setCreateTime(new Date());             //创建时间
           payments.setBillId(fr.getBillNo());
           int paymentRows  = iFranchisePaymentsService.insertFranchisePayments(payments);
           if (paymentRows > 0){
               return AjaxResult.success("支付记录创建成功");
           }else {
               return AjaxResult.success("支付记录创建失败");
           }

       }catch (Exception e){
           return AjaxResult.error("创建支付记录失败");
       }
    }


}
